package com.dinree.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.base.library.BaseActivity;
import com.base.library.widget.CompetitionWebChromeClient;
import com.dinree.R;
import com.dinree.bean.UserBean;
import com.dinree.databinding.ActivityGoodsWebBinding;
import com.jakewharton.rxbinding2.view.RxView;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.base.library.Constant.WINDOW_DURATION;

public class GoodsWebActivity extends BaseActivity {
    private ActivityGoodsWebBinding activityGoodsWebBinding;
    private FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
    private UserBean userBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_web;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        activityGoodsWebBinding = getViewDataBinding();
        userBean = realm.findFirst(UserBean.class);
        String url = getIntent().getStringExtra("url");
        activityGoodsWebBinding.webView.addJavascriptInterface(new JSHook(), "dinree");
        if (userBean != null) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("user_id", userBean.user_id);
            map.put("user_token", userBean.user_token);
            map.put("referer", "https://web.dinree.cn/epsea/front");
            activityGoodsWebBinding.webView.loadUrl(url, map);
        } else {
            activityGoodsWebBinding.webView.loadUrl(url);
        }
        activityGoodsWebBinding.webView.setWebChromeClient(new CompetitionWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);

            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setTitle(title);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissionsCallback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                super.onShowCustomView(view, customViewCallback);
            }
        });
        activityGoodsWebBinding.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityGoodsWebBinding.webView.loadUrl("javascript:share('android')");
            }
        });
        RxView.clicks(activityGoodsWebBinding.btnBack).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            finish();
        });
        initIndicator();
    }

    public class JSHook {
        @JavascriptInterface
        public void close() {
            finish();
        }

        @JavascriptInterface
        public void setShareInfo(String type, String title, String content, String imgUrl, String url) {
            UMShareConfig config = new UMShareConfig();
            config.setShareToQQFriendQzoneItemHide(true);
            UMShareAPI.get(mContext).setShareConfig(config);
            SHARE_MEDIA share_media = null;
            if (type.equals("wx")) {
                share_media = SHARE_MEDIA.WEIXIN;
            }
            if (type.equals("wx_friend")) {
                share_media = SHARE_MEDIA.WEIXIN_CIRCLE;
            }
            if (type.equals("qq")) {
                share_media = SHARE_MEDIA.QQ;
            }
            if (type.equals("sina")) {
                share_media = SHARE_MEDIA.SINA;
            }
            if (type.equals("qzone")) {
                share_media = SHARE_MEDIA.QZONE;
            }
            UMWeb web = new UMWeb(url);
            web.setTitle(title);//标题
            web.setThumb(new UMImage(mContext, imgUrl));  //缩略图
            web.setDescription(content);//描述
            new ShareAction(GoodsWebActivity.this)
                    .setPlatform(share_media)//传入平台
                    .withMedia(web)
                    .setCallback(shareListener)//回调监听器
                    .share();

        }

        @JavascriptInterface
        public void updateDisplay(String type) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (type.equals("goods")) {
                        mFragmentContainerHelper.handlePageSelected(0);
                    }
                    if (type.equals("details")) {
                        mFragmentContainerHelper.handlePageSelected(1);
                    }
                    if (type.equals("comment")) {
                        mFragmentContainerHelper.handlePageSelected(2);
                    }
                }
            });
        }
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void initIndicator() {
        List<String> titles = new ArrayList<>();
        titles.add("商品");
        titles.add("详情");
        titles.add("评价");
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(context.getResources().getColor(R.color.white_65));
                colorTransitionPagerTitleView.setSelectedColor(context.getResources().getColor(R.color.white));
                colorTransitionPagerTitleView.setText(titles.get(index));
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mFragmentContainerHelper.handlePageSelected(index);
                        String js = "";
                        switch (index) {
                            case 0:
                                js = "javascript:switchDisplay('goods')";
                                break;
                            case 1:
                                js = "javascript:switchDisplay('details')";
                                break;
                            case 2:
                                js = "javascript:switchDisplay('comment')";
                                break;
                        }
                        activityGoodsWebBinding.webView.loadUrl(js);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                indicator.setColors(context.getResources().getColor(R.color.white));
                return indicator;
            }
        });
//        commonNavigator.setAdjustMode(true);//平分布局
        activityGoodsWebBinding.magicIndicator.setNavigator(commonNavigator);
        mFragmentContainerHelper.attachMagicIndicator(activityGoodsWebBinding.magicIndicator);

//        ViewPagerHelper.bind(activityGoodsWebBinding.magicIndicator, activityGoodsWebBinding.contentViewPager);
    }
}

